package com.zjj.algorithm.learning.atguigu.sort;

import java.util.Arrays;

/**
 * 堆排序
 * 使用选择排序，排 80000 个数据，用时 10 ms
 *
 * @author zjj_admin
 * @date 2022/11/27 15:26
 */
public class HeapSort {

    public static void main(String[] args) {
        int[] arr = new int[]{4, 6, 8, 5, 9, 8, 9, 6, 12, 56, 3, 25};
        heapSort(arr);

        //测试排 80000 个数据用时
//        int[] arr = new int[80000];
//        for (int i = 0; i < arr.length; i++) {
//            arr[i] = (int) (Math.random() * 800000);
//        }
//        long time1 = System.currentTimeMillis();
//
//        heapSort(arr);
//        long time2 = System.currentTimeMillis();
//        System.out.printf("使用选择排序，排 %d 个数据，用时 %s ms", arr.length, (time2 - time1));
    }


    public static void heapSort(int[] arr) {
//        adjustHeap(arr,1,arr.length);
//        System.out.println("arr = " + Arrays.toString(arr));
//
//        adjustHeap(arr,0,arr.length);
//        System.out.println("arr = " + Arrays.toString(arr));

        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            adjustHeap(arr, i, arr.length);
        }
        int temp;
        for (int j = arr.length - 1; j > 0; j--) {
            temp = arr[j];
            arr[j] = arr[0];
            arr[0] = temp;
            adjustHeap(arr, 0, j);
        }
        System.out.println("arr = " + Arrays.toString(arr));
    }


    /**
     *        6
     *    5       4
     * 8    9   6
     */

    /**
     * @param arr
     * @param i
     * @param length
     */
    public static void adjustHeap(int[] arr, int i, int length) {

        int temp = arr[i];


        for (int k = i * 2 + 1; k < length; k = 2 * k + 1) {
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k++;
            }
            if (arr[k] > temp) {
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }
        arr[i] = temp;

    }
}
